
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { ref, reactive, nextTick, watch, onMounted } from "vue";
import { ObtainInternalRatingResultBaseData, InternalRatingResultsObtainList, ObtainInternalRatingResult, QueryInternalRatingResultChart, QueryInternalRatingResultUserInfo, ApplicationRatingResults } from "@/api/stu/bankBigData";
import { Pie } from '@antv/g2plot';
import { useRoute } from "vue-router";
import qs from "qs";
export function useGradeResult() {
  const route = useRoute();
  const dataList = ref<any>([]);
  const loading = ref<boolean>(true);
  const CreditVisible = ref<boolean>(false);
  const applyVisible = ref<boolean>(false);
  const chartVisible = ref<boolean>(false);
  const selectData = ref()
  const chartList = ref([])
  const infoList = ref()
  const selectListId = ref()
  const resultVisible = ref<boolean>(false);
  const applyCheck = ref([])
  const showCustomType = ref(false)
  const gradeType = ref('')
  //右边显示
  const showText = reactive({
    tittle: '',
    tittle1: '',
    content: '',
  })
  const formData = reactive({
    id: '',
    type: ''
  })
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const pagination1 = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "模型名称",
      prop: "userModelName",
      minWidth: 200
    },
    {
      label: "客户类型",
      prop: "customerType",
      minWidth: 100
    },
    {
      label: "操作",
      fixed: "right",
      width: 300,
      slot: "operation"
    }
  ];
  const columns2: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "公司名称",
      prop: "companyName",
      minWidth: 200,
    },
    {
      label: "法人姓名",
      prop: "legalPersonName",
      minWidth: 100,
    },
    {
      label: "法人证件号",
      prop: "corporateIdNumber",
      minWidth: 200
    },
    {
      label: "法人联系方式",
      prop: "legalPersonContact",
      minWidth: 200,
    },

    {
      label: "所属行业",
      prop: "industry",
      minWidth: 150,
    },
    {
      label: "成立时间",
      prop: "establishmentTime",
      minWidth: 150
    },
    {
      label: "公司规模",
      prop: "companySize",
      minWidth: 100
    },
    {
      label: "竞争优势",
      prop: "competitiveAdvantage",
      minWidth: 200
    },
    {
      label: "管理层素质",
      prop: "managementQuality",
      minWidth: 200
    },
    {
      label: "信用记录",
      prop: "creditHistory",
      minWidth: 150
    },
    {
      label: "逾期情况",
      prop: "overdueSituation",
      minWidth: 150,
    },
    {
      label: "每股净资产（元）",
      prop: "netAssetsPerShare",
      minWidth: 150,
    },
    {
      label: "总资产利润率（%）",
      prop: "totalAssetProfitMargin",
      minWidth: 150
    },
    {
      label: "销售毛利率（%）",
      prop: "salesGrossProfitMargin",
      minWidth: 200,
    },

    {
      label: "流动比率（%)",
      prop: "currentRatio",
      minWidth: 150,
    },
    {
      label: "速动比率(%)",
      prop: "quickRatio",
      minWidth: 150
    },
    {
      label: "净利润增长率(%)",
      prop: "netProfitGrowthRate",
      minWidth: 200
    },
    {
      label: "应收账款周转天数(天)",
      prop: "daysAccountsReceivableTurnover",
      minWidth: 200
    },
    {
      label: "固定资产周转率(%)",
      prop: "fixedAssetTurnoverRate",
      minWidth: 200
    },
    {
      label: "存货周转天数(天)",
      prop: "inventoryTurnoverDays",
      minWidth: 200
    },
    {
      label: "发展前景",
      prop: "developmentProspects",
      minWidth: 150
    },
    {
      label: "公司结构",
      prop: "companyStructure",
      minWidth: 100,
    },
    {
      label: "经营管理",
      prop: "companyStructure",
      minWidth: 100,
    },
    {
      label: "偿债能力",
      prop: "debtPayingAbility",
      minWidth: 100
    },
    {
      label: "财务管理",
      prop: "financialManagement",
      minWidth: 200,
    },

    {
      label: "行业前景",
      prop: "industryProspects",
      minWidth: 150,
    },
    {
      label: "是否有国家扶持",
      prop: "isHaveNationalSupport",
      minWidth: 150
    },
    {
      label: "是否有地方扶持",
      prop: "isHaveLocalSupport",
      minWidth: 150
    },
    {
      label: "同行认可度",
      prop: "peerRecognition",
      minWidth: 200
    },
    {
      label: "企业声誉",
      prop: "corporateReputation",
      minWidth: 200
    },
    {
      label: "违规频率",
      prop: "violationFrequency",
      minWidth: 150
    },
  ];
  const columns3: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 120
    },
    {
      label: "姓名",
      prop: "userName",
      minWidth: 100,
    },
    {
      label: "性别",
      prop: "gender",
      minWidth: 100
    },
    {
      label: "年龄",
      prop: "age",
      minWidth: 100
    },
    {
      label: "平均月收入",
      prop: "avgMonthlyIncome",
      minWidth: 200,
    },

    {
      label: "配偶平均月收入",
      prop: "spouseAvgMonthlyIncome",
      minWidth: 150,
    },
    {
      label: "收入来源",
      prop: "sourceIncome",
      minWidth: 150
    },
    {
      label: "收入稳定性",
      prop: "incomeStability",
      minWidth: 100
    },
    {
      label: "财务状况",
      prop: "financialCondition",
      minWidth: 200
    },
    {
      label: "资产规模",
      prop: "assetSize",
      minWidth: 200
    },
    {
      label: "借贷历史",
      prop: "loanHistory",
      minWidth: 150
    },
    {
      label: "借贷信用",
      prop: "loanCredit",
      minWidth: 100,
    },
    {
      label: "欠款情况",
      prop: "debtSituation",
      minWidth: 100,
    },
    {
      label: "风险偏好",
      prop: "riskAppetite",
      minWidth: 100
    },
    {
      label: "承受能力",
      prop: "affordability",
      minWidth: 200,
    },

    {
      label: "工作稳定性",
      prop: "workStability",
      minWidth: 150,
    },
    {
      label: "职业背景",
      prop: "careerBackground",
      minWidth: 150
    },
    {
      label: "居住稳定性",
      prop: "residentialStability",
      minWidth: 100
    },
    {
      label: "所属行业前景",
      prop: "industryProspects",
      minWidth: 200
    },
    {
      label: "是否在黑名单",
      prop: "isBlacklist",
      minWidth: 200
    },
    {
      label: "是否有恶意透支行为",
      prop: "isHaveOverdraftBehavior",
      minWidth: 150
    },
    {
      label: "征信查询频率",
      prop: "creditInquiryFrequency",
      minWidth: 100,
    },
    {
      label: "个人竞争力",
      prop: "personalCompetitiveness",
      minWidth: 100,
    },
    {
      label: "家庭条件",
      prop: "familyConditions",
      minWidth: 100
    },

  ];
  const selectApplyList = [{
    label: '客户授信准入',
    value: 'IsCustomerCreditAdmission'
  },
  {
    label: '预期损失和经济资本计量',
    value: 'IsExpectedLossesRc'
  },
  {
    label: '绩效考核',
    value: 'IsPerformanceAppraisal'
  },
  {
    label: '减值准备计提',
    value: 'IsProvisionForImpairment'
  },]
  const BtnLoading = ref<boolean>(false)
  function OUTBtnLoding() {
    setTimeout(() => {
      BtnLoading.value = false
    }, 1000)
  }
  function handleSizeChange() {
    getList()
  }

  function handleCurrentChange() {
    getList()
  }


  function handleSizeChange2() {
    getList2()
  }

  function handleCurrentChange2() {
    getList2()
  }


  // 获取信用评分数据
  async function getList() {
    const data = {
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      planId: route.query.planId,
      taskId: route.query.taskId,
    }
    const res = await InternalRatingResultsObtainList(data);
    if (res.success) {
      pagination.total = res.data.totalCount;
      res.data?.items.forEach(item => {
        item.createTime = item.createTime.substring(0, 10)
      })
      dataList.value = res.data.items;
      loading.value = false;
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => {
        loading.value = false;
      }, 1500)
    }
  }
  async function addList() {
    const data = {
      planId: route.query.planId,
      taskId: route.query.taskId,
      studentAnswer: JSON.stringify(formData.id),
      detailId: formData.id
    }
    BtnLoading.value = true;
    OUTBtnLoding()
    let res = await ObtainInternalRatingResult(data)
    if (res.status == 200) {
      ElMessage.success(res.msg);
      applyVisible.value = false
      for (let variable in formData) {
        formData[variable] = '';
      }
      getList()
    } else {
      ElMessage.error(res.msg);
    }
  }

  function selectId(val) {
    setTimeout(() => {
      formData.type = selectData.value.filter(item => item.internalRatingModelId == formData.id)[0].customerTypeDesc
    }, 100)
  }
  async function showEcharts(row) {
    //更换columns
    if (row.customerType !== '公司客户') {
      showCustomType.value = true
    } else {
      showCustomType.value = false
    }

    chartVisible.value = true
    //获取echatrs数据
    selectListId.value = row.internalRatingResultsObtainId
    const params = {
      planId: route.query.planId,
      taskId: route.query.taskId,
      detailId: row.internalRatingResultsObtainId
    }
    const res = await QueryInternalRatingResultChart(params)
    if (res.status == 200) {
      const data = []
      res.data.forEach(item => {
        item.evaluationGradeDesc = item.evaluationGradeDesc.replace(/^\r\n|\r\n$/g, "");
        console.log(item.evaluationGradeDesc);

        data.push({
          type: item.evaluationGrade,
          value: item.customerNum,
          desc: item.evaluationGradeDesc
        })
      })
      let order = ["AAA", "AA", "A", "BBB", "BB", "B", "CCC", "CC", "C", "D"];
      data.sort((a, b) => {
        return order.indexOf(a.type) - order.indexOf(b.type);
      });
      chartList.value = data
      const piePlot = new Pie('container', {
        appendPadding: 10,
        data,
        angleField: 'value',
        colorField: 'type',
        radius: 0.9,
        color: ['#19CAAD', '#8CC7B5', '#A0EEE1', '#BEE7E9', '#BEEDC7', '#D6D5B7', '#D1BA74', '#E6CEAC', '#ECAD9E', '#F4606C'],
        label: {
          type: 'inner',
          offset: '10%',
          content: ({ percent }) => `${(percent * 100).toFixed(0)}%`,
          style: {
            fontSize: 14,
            textAlign: 'center',
          },
        },
        interactions: [{ type: 'element-active' }],
      })
      piePlot.on('element:click', (ev) => {
        gradeType.value = ev.data.data.type
        pagination1.currentPage = 1
        getList2()
      });
      piePlot.on('element:mouseenter', (ev) => {
        const split_data = ev.data.data.desc.split("\r\n")
        showText.tittle = split_data[0];
        showText.content = split_data[2];
        showText.tittle1 = split_data[1]

      });
      // piePlot.on('element:mouseleave', (ev) => {
      //   showText.tittle = '';
      //   showText.content = '';
      //   showText.tittle1 = ''
      // });
      piePlot.render()
      const split_data = data[0].desc.split("\r\n")
      showText.tittle = split_data[0];
      showText.content = split_data[2];
      showText.tittle1 = split_data[1]
    } else {
      ElMessage.error(res.msg);
    }
    getList2()
  }
  async function getList2() {
    //获取echatrs数据
    const data = {
      pageIndex: pagination1.currentPage,
      pageCount: pagination1.pageSize,
      planId: route.query.planId,
      taskId: route.query.taskId,
      detailId: selectListId.value,
      grade: gradeType.value || ''
    }
    const res = await QueryInternalRatingResultUserInfo(data)
    if (res.status == 200) {
      pagination1.total = res.data.totalCount;
      infoList.value = res.data.items;
      if (!!gradeType.value) {
        ElMessage.success(`级别为${gradeType.value}的数据已刷新`);
      }
    } else {
      ElMessage.error(res.msg);
    }
  }

  function showDetail(row) {
    selectListId.value = row.internalRatingResultsObtainId
    resultVisible.value = true
  }

  async function addApply() {
    if (applyCheck.value.length == 0) {
      ElMessage.warning('请先选择结果应用！')
      return
    }
    const data = {
      planId: route.query.planId,
      taskId: route.query.taskId,
      internalRatingResultsObtainId: selectListId.value,
      IsCustomerCreditAdmission: 0,
      IsExpectedLossesRc: 0,
      IsPerformanceAppraisal: 0,
      IsProvisionForImpairment: 0,
    }
    applyCheck.value.forEach(item => {
      if (item == 'IsCustomerCreditAdmission') {
        data.IsCustomerCreditAdmission = 1
      }
      if (item == 'IsExpectedLossesRc') {
        data.IsExpectedLossesRc = 1
      }
      if (item == 'IsPerformanceAppraisal') {
        data.IsPerformanceAppraisal = 1
      }
      if (item == 'IsProvisionForImpairment') {
        data.IsProvisionForImpairment = 1
      }
    })
    data.studentAnswer = JSON.stringify(data)
    BtnLoading.value = true;
    OUTBtnLoding()
    let res = await ApplicationRatingResults(data)
    if (res.status == 200) {
      applyCheck.value = []
      resultVisible.value = false
      getList()
      ElMessage.success(res.msg);
    } else {
      ElMessage.error(res.msg);
    }
  }

  function cancelResult() {
    resultVisible.value = false
    applyCheck.value = []
  }
  onMounted(async () => {
    const data = {
      planId: route.query.planId,
      taskId: route.query.taskId,
    }
    let res = await ObtainInternalRatingResultBaseData(data)
    if (res.success) {
      selectData.value = res?.data
    } else {
      ElMessage.error(res.msg);
    }
    getList()
  })

  return {
    dataList,
    loading,
    CreditVisible,
    pagination,
    columns,
    selectData,
    BtnLoading,
    handleCurrentChange,
    handleSizeChange,
    applyVisible,
    formData,
    addList,
    selectId,
    showEcharts,
    chartVisible,
    chartList,
    infoList,
    pagination1,
    columns2,
    handleCurrentChange2,
    handleSizeChange2,
    resultVisible,
    applyCheck,
    showDetail,
    selectApplyList,
    addApply,
    showText,
    showCustomType,
    columns3,
    cancelResult
  }
}
